import { Role } from '../models/Role.js';
import { Permission } from '../models/Permission.js';
import { RolePermission } from '../models/RolePermission.js';
import { UserRole } from '../models/UserRole.js';

const roleModel = new Role();
const permissionModel = new Permission();
const rolePermissionModel = new RolePermission();
const userRoleModel = new UserRole();

export class PermissionController {
    // 获取所有角色
    async getRoles(req, res) {
        try {
            console.log('=== 获取角色列表 ===');
            const allRoles = roleModel.findAll();
            console.log('所有角色:', allRoles);
            const roles = allRoles.filter(r => r.status === 'active');
            console.log('激活的角色:', roles);
            res.json({
                success: true,
                data: roles
            });
        } catch (error) {
            console.error('获取角色列表失败:', error);
            res.status(500).json({
                success: false,
                error: '获取角色列表失败',
                message: error.message
            });
        }
    }

    // 获取所有权限
    async getPermissions(req, res) {
        try {
            console.log('=== 获取权限列表 ===');
            const { resource, type } = req.query;
            let permissions = permissionModel.findAll();
            console.log('所有权限数量:', permissions.length);

            if (resource) {
                permissions = permissions.filter(p => p.resource === resource);
            }
            if (type) {
                permissions = permissions.filter(p => p.type === type);
            }

            res.json({
                success: true,
                data: permissions
            });
        } catch (error) {
            console.error('获取权限列表失败:', error);
            res.status(500).json({
                success: false,
                error: '获取权限列表失败',
                message: error.message
            });
        }
    }

    // 获取角色的权限
    async getRolePermissions(req, res) {
        try {
            const { roleId } = req.params;
            const roleIdNum = parseInt(roleId);

            // 管理员角色自动拥有所有权限
            if (roleIdNum === 1) {
                const allPermissions = permissionModel.findAll();
                return res.json({
                    success: true,
                    data: allPermissions.map(p => ({
                        id: p.id,
                        name: p.name,
                        code: p.code,
                        resource: p.resource,
                        action: p.action,
                        type: p.type,
                        description: p.description
                    }))
                });
            }

            const rolePermissions = rolePermissionModel.findByRoleId(roleIdNum);
            const permissionIds = rolePermissions.map(rp => rp.permissionId);
            const permissions = permissionModel.findAll()
                .filter(p => permissionIds.includes(p.id));

            res.json({
                success: true,
                data: permissions.map(p => ({
                    id: p.id,
                    name: p.name,
                    code: p.code,
                    resource: p.resource,
                    action: p.action,
                    type: p.type,
                    description: p.description
                }))
            });
        } catch (error) {
            console.error('获取角色权限失败:', error);
            res.status(500).json({
                success: false,
                error: '获取角色权限失败',
                message: error.message
            });
        }
    }

    // 批量更新角色权限
    async updateRolePermissions(req, res) {
        try {
            const { roleId, permissionIds } = req.body;

            console.log('=== 更新角色权限 ===');
            console.log('收到的roleId:', roleId, typeof roleId);
            console.log('收到的permissionIds:', permissionIds, Array.isArray(permissionIds));

            if (!roleId || !Array.isArray(permissionIds)) {
                return res.status(400).json({
                    success: false,
                    error: 'roleId和permissionIds为必填项，permissionIds必须是数组'
                });
            }

            // 确保roleId是数字
            const roleIdNum = parseInt(roleId);
            if (isNaN(roleIdNum)) {
                return res.status(400).json({
                    success: false,
                    error: 'roleId必须是有效的数字'
                });
            }

            // 管理员角色（roleId=1）自动拥有所有权限，不允许修改
            if (roleIdNum === 1) {
                // 确保管理员拥有所有权限
                const allPermissions = permissionModel.findAll();
                rolePermissionModel.removeAllRolePermissions(roleIdNum);
                const results = [];
                for (const permission of allPermissions) {
                    const result = rolePermissionModel.addRolePermission(roleIdNum, permission.id);
                    results.push(result);
                }

                console.log('管理员权限已自动分配所有权限，共', results.length, '个');
                return res.json({
                    success: true,
                    message: '管理员角色自动拥有所有权限，已自动分配所有权限',
                    data: results
                });
            }

            // 确保permissionIds都是数字
            const permissionIdNums = permissionIds.map(id => parseInt(id)).filter(id => !isNaN(id));
            console.log('转换后的permissionIdNums:', permissionIdNums);

            // 先移除所有现有权限
            const removedCount = rolePermissionModel.removeAllRolePermissions(roleIdNum);
            console.log(`移除角色 ${roleIdNum} 的现有权限，移除了 ${removedCount ? '一些' : '0'} 个权限`);

            // 添加新权限
            const results = [];
            for (const permissionId of permissionIdNums) {
                const result = rolePermissionModel.addRolePermission(roleIdNum, permissionId);
                results.push(result);
                console.log(`添加权限: roleId=${roleIdNum}, permissionId=${permissionId}`, result);
            }

            console.log(`角色 ${roleIdNum} 权限更新完成，共 ${results.length} 个权限`);

            res.json({
                success: true,
                message: `角色权限更新成功，已分配 ${results.length} 个权限`,
                data: results
            });
        } catch (error) {
            console.error('更新角色权限失败:', error);
            res.status(500).json({
                success: false,
                error: '更新角色权限失败',
                message: error.message
            });
        }
    }

    // 获取当前用户的权限信息
    async getCurrentUserPermissions(req, res) {
        try {
            const userId = req.userId;

            if (!userId) {
                return res.status(401).json({
                    success: false,
                    error: '未认证'
                });
            }

            // 获取用户的角色
            const userRoles = userRoleModel.findByUserId(userId);
            const roleIds = userRoles.map(ur => ur.roleId);
            const roles = roleModel.findAll().filter(r => roleIds.includes(r.id));

            // 检查是否是管理员
            const isAdmin = roleIds.includes(1);

            let permissions;
            if (isAdmin) {
                // 管理员拥有所有权限
                permissions = permissionModel.findAll();
            } else {
                // 获取角色的权限
                const rolePermissions = rolePermissionModel.findAll()
                    .filter(rp => roleIds.includes(rp.roleId));

                const permissionIds = [...new Set(rolePermissions.map(rp => rp.permissionId))];
                permissions = permissionModel.findAll()
                    .filter(p => permissionIds.includes(p.id));
            }

            res.json({
                success: true,
                data: {
                    roles: roles.map(r => ({
                        id: r.id,
                        name: r.name,
                        code: r.code,
                        description: r.description
                    })),
                    permissions: permissions.map(p => ({
                        id: p.id,
                        name: p.name,
                        code: p.code,
                        resource: p.resource,
                        action: p.action,
                        type: p.type
                    })),
                    permissionCodes: permissions.map(p => p.code),
                    roleCodes: roles.map(r => r.code),
                    isAdmin: isAdmin
                }
            });
        } catch (error) {
            console.error('获取用户权限失败:', error);
            res.status(500).json({
                success: false,
                error: '获取权限失败',
                message: error.message
            });
        }
    }
}

